package com.yunbiao.ybbusstopplate.utils

import android.text.TextUtils
import android.util.Log
import com.blankj.utilcode.util.FileUtils
import com.example.library_hy_advert.system.Path
import com.yunbiao.ybbusstopplate.base.Constants
import com.yunbiao.ybbusstopplate.bean.ResouceBean
import com.yunbiao.ybbusstopplate.utils.cache.LayoutCache
import com.yunbiao.ybbusstopplate.utils.core.SSTool
import com.yunbiao.ybbusstopplate.utils.core.play.ImageDetail
import com.yunbiao.ybbusstopplate.utils.core.play.LayoutInfo
import com.yunbiao.ybbusstopplate.utils.core.play.LayoutJsonTool
import com.yunbiao.ybbusstopplate.utils.net.ResourceUpdate
import org.json.JSONArray
import java.io.File
import java.util.regex.Pattern

class FileTool {
    companion object{
        private val MIME_MapTable = arrayOf(
                arrayOf(".mkv", "video/mkv"),
                arrayOf(".mov", "video/mov"),
                arrayOf(".rm", "video/rm"),
                arrayOf(".rmvb", "video/rmvb"),
                arrayOf(".amr", "audio/amr"),
                arrayOf(".flv", "video/flv"),
                arrayOf(".3gp", "video/3gpp"),
                arrayOf(".apk", "application/vnd.android.package-archive"),
                arrayOf(".asf", "video/x-ms-asf"),
                arrayOf(".avi", "video/x-msvideo"),
                arrayOf(".bin", "application/octet-stream"),
                arrayOf(".c", "text/plain"),
                arrayOf(".class", "application/octet-stream"),
                arrayOf(".conf", "text/plain"),
                arrayOf(".cpp", "text/plain"),
                arrayOf(".doc", "application/msword"),
                arrayOf(".exe", "application/octet-stream"),
                arrayOf(".gtar", "application/x-gtar"),
                arrayOf(".gz", "application/x-gzip"),
                arrayOf(".h", "text/plain"),
                arrayOf(".htm", "text/html"),
                arrayOf(".html", "text/html"),
                arrayOf(".jar", "application/java-archive"),
                arrayOf(".java", "text/plain"),
                arrayOf(".bmp", "image/bmp"),
                arrayOf(".gif", "image/gif"),
                arrayOf(".png", "image/png"),
                arrayOf(".jpeg", "image/jpeg"),
                arrayOf(".jpg", "image/jpeg"),
                arrayOf(".js", "js/javascript"),
                arrayOf(".css", "js/javascript"),
                arrayOf(".log", "text/plain"),
                arrayOf(".m3u", "audio/x-mpegurl"),
                arrayOf(".m4a", "audio/mp4a-latm"),
                arrayOf(".m4b", "audio/mp4a-latm"),
                arrayOf(".m4p", "audio/mp4a-latm"),
                arrayOf(".m4u", "video/vnd.mpegurl"),
                arrayOf(".m4v", "video/x-m4v"),
                arrayOf(".mov", "video/quicktime"),
                arrayOf(".mp2", "audio/x-mpeg"),
                arrayOf(".mp3", "audio/x-mpeg"),
                arrayOf(".mp4", "video/mp4"),
                arrayOf(".ts", "video/ts"),
                arrayOf(".mpc", "application/vnd.mpohun.certificate"),
                arrayOf(".mpe", "video/mpeg"),
                arrayOf(".mpeg", "video/mpeg"),
                arrayOf(".mpg", "video/mpeg"),
                arrayOf(".mpg4", "video/mp4"),
                arrayOf(".mpga", "audio/mpeg"),
                arrayOf(".msg", "application/vnd.ms-outlook"),
                arrayOf(".ogg", "audio/ogg"),
                arrayOf(".pdf", "application/pdf"),
                arrayOf(".pps", "application/vnd.ms-powerpoint"),
                arrayOf(".ppt", "application/vnd.ms-powerpoint"),
                arrayOf(".prop", "text/plain"),
                arrayOf(".rar", "application/x-rar-compressed"),
                arrayOf(".rc", "text/plain"),
                arrayOf(".rtf", "application/rtf"),
                arrayOf(".sh", "text/plain"),
                arrayOf(".tar", "application/x-tar"),
                arrayOf(".tgz", "application/x-compressed"),
                arrayOf(".txt", "text/plain"),
                arrayOf(".wav", "audio/x-wav"),
                arrayOf(".wma", "audio/x-ms-wma"),
                arrayOf(".wmv", "audio/x-ms-wmv"),
                arrayOf(".wmv", "video/wmv"),
                arrayOf(".wps", "application/vnd.ms-works"),
                arrayOf(".xml", "text/xml"),
                arrayOf(".xml", "text/plain"),
                arrayOf(".z", "application/x-compress"),
                arrayOf(".zip", "application/zip"),
                arrayOf("", "*/*")
        )

        private fun getFileType(file: String): Int {
            val mime = getMIMEType(file)
            return if (mime.contains("image")) {
                FileType.IMAGE
            } else if (mime.contains("audio")) {
                FileType.VOICE
            } else if (mime.contains("video")) {
                FileType.VIDEO
            } else if (mime.contains("js") || mime.contains("css")) {
                FileType.JS
            } else if (mime.contains("application")) {
                FileType.APP
            } else if (mime.contains("text")) {
                FileType.TEXT_FILE
            } else {
                0
            }
        }

        fun getMIMEType(fName: String): String {
            var type = "*/*"
            if (!TextUtils.isEmpty(fName)) {
                val dotIndex = fName.lastIndexOf(".")
                if (dotIndex < 0) {
                    return type
                }
                val end = fName.substring(dotIndex, fName.length).toLowerCase()
                if (TextUtils.isEmpty(end)) {
                    return type
                }
                for (aMIME_MapTable in MIME_MapTable) {
                    if (end == aMIME_MapTable[0]) type = aMIME_MapTable[1]
                }
            }
            return type
        }

        fun isImage(path: String): Boolean {
            return getFileType(path) == FileType.IMAGE
        }

        fun isJsFile(path: String): Boolean {
            return getFileType(path) == FileType.JS
        }

        fun isVideo(path: String): Boolean {
            return getFileType(path) == FileType.VIDEO
        }

        fun isMusic(path: String): Boolean {
            return getFileType(path) == FileType.VOICE
        }

        fun isWeb(path: String?): Boolean {
            val reg = "^((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+" //判断网址URL的正则表达式
            val pattern = Pattern.compile(reg)
            return pattern.matcher(path).matches()
        }

        //获取文件夹下所有图片、视频资源
        fun getResourceList(filePath: String):List<ResouceBean>{
            var resouceList= arrayListOf<ResouceBean>()
            val parentFile = File(filePath)
            if (parentFile!=null&&parentFile.exists()&&parentFile.isDirectory){
                val chiledenFilePathList = parentFile.listFiles()
                for (file in chiledenFilePathList){
                    val path = file.absolutePath
                    if (isImage(path)){
                        val resouceBean = ResouceBean(path, FileType.IMAGE)
                        resouceList.add(resouceBean)
                    }else if (isVideo(path)){
                        val resouceBean = ResouceBean(path, FileType.VIDEO)
                        resouceList.add(resouceBean)
                    }
                }
            }
            return resouceList
        }

        //获取文件夹下所有图片、视频资源
        fun getOnlineResourceList(screenArray: JSONArray):List<ResouceBean>{
            var resouceList= arrayListOf<ResouceBean>()
            for (i in 0.. screenArray.length()-1){
                try {
                  var  layoutJson =   screenArray.getJSONObject(i)
                    var layoutList: List<LayoutInfo> = LayoutJsonTool.getLayoutInfo(layoutJson.toString())
                    if (layoutList != null && layoutList.size > 0) {
                        for (j in layoutList.indices) {

                            var layoutInfo = layoutList[j]

                            var layoutType = layoutInfo.type
                            // 添加自动播放
                            var imageDetail: ImageDetail = layoutInfo.imageDetail
                            when(layoutType){
                                1 -> {
                                    var imageArray = layoutInfo.content
                                    for (anImageArray in imageArray) {
                                        Log.e("FileTool", "getOnlineResourceList: -----11111111111111111" )
                                        var resouceBean = ResouceBean()
//                                        var path: String =
//                                            ResourceUpdate.RESOURSE_PATH + ResourceUpdate.IMAGE_CACHE_PATH.toString() + anImageArray
                                        // 设置 中部广告 资源位置
                                        var path: String = File(Path.getAdvertCenterPath(),anImageArray).absolutePath

                                        var result =  LayoutCache.getLayoutCacheAsString();
                                        var advertType =  SSTool.getAdvertType(result)

                                        Log.d("net", "autoPlayView 能区分 advertType 吗？advertType: " + advertType)

                                        Log.e(
                                            "FileTool",
                                            "getOnlineResourceList: ----------------path------------->" + path
                                        )
                                        Log.e("FileTool", "getOnlineResourceList: -----222---------->"+path )

                                        // 设置 中部广告 资源位置
                                        //path = Constants.advertCenterResourcePath
                                        Log.d("net", "检查 fileTool.kt 设置 中部广告 资源位置: " + path + " --- " + FileUtils.isFileExists(path))

                                        resouceBean.path = path
                                        if (File(path + "_ok").exists()) { //如果存在ok文件就添加到播放列表中
                                            Log.e("FileTool", "getOnlineResourceList: -----333---------->" )
                                            if (isImage(path)) {
                                                Log.e("FileTool", "getOnlineResourceList: -----333-----11----->" )
                                                resouceBean.type = FileType.IMAGE
                                            } else if (isVideo(path)) {
                                                Log.e("FileTool", "getOnlineResourceList: -----333---222------->" )
                                                resouceBean.type = FileType.VIDEO
                                            }
                                            var playTime = 5
                                            try {
                                                playTime = imageDetail.playTime.toInt()
                                            } catch (e: java.lang.Exception) {
                                                e.printStackTrace();
                                            }
                                            resouceBean.playTime = playTime
                                            Log.e("FileTool", "getOnlineResourceList: -----4444---------->" )
                                        }
                                        Log.e("FileTool", "getOnlineResourceList: -----55555---------->" )
                                        resouceList.add(resouceBean)
                                    }
                                }

                            }

                        }
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return resouceList
        }

        fun getOnlineResourceListBottom(screenArray: JSONArray):List<ResouceBean>{
            var resouceList= arrayListOf<ResouceBean>()
            for (i in 0.. screenArray.length()-1){
                try {
                    var  layoutJson =   screenArray.getJSONObject(i)
                    var layoutList: List<LayoutInfo> = LayoutJsonTool.getLayoutInfo(layoutJson.toString())
                    if (layoutList != null && layoutList.size > 0) {
                        for (j in layoutList.indices) {

                            var layoutInfo = layoutList[j]

                            var layoutType = layoutInfo.type
                            // 添加自动播放
                            var imageDetail: ImageDetail = layoutInfo.imageDetail
                            when(layoutType){
                                1 -> {
                                    var imageArray = layoutInfo.content
                                    for (anImageArray in imageArray) {
                                        Log.e("FileTool", "getOnlineResourceList: -----11111111111111111" )
                                        var resouceBean = ResouceBean()
//                                        var path: String =
//                                            ResourceUpdate.RESOURSE_PATH + ResourceUpdate.IMAGE_CACHE_PATH.toString() + anImageArray
                                        // 设置 底部广告 资源位置
                                        var path: String = File(Path.getAdvertBottomPath(),anImageArray).absolutePath

                                        var result =  LayoutCache.getLayoutCacheAsStringBottom();
                                        var advertType =  SSTool.getAdvertType(result)

                                        Log.d("net", "autoPlayView 能区分 advertType 吗？advertType: " + advertType)

                                        Log.e(
                                            "FileTool",
                                            "getOnlineResourceList: ----------------path------------->" + path
                                        )
                                        Log.e("FileTool", "getOnlineResourceList: -----222---------->"+path )

                                        // 设置 中部广告 资源位置
                                        //path = Constants.advertCenterResourcePath
                                        Log.d("net", "检查 fileTool.kt 设置 中部广告 资源位置: " + path)

                                        resouceBean.path = path
                                        if (File(path + "_ok").exists()) { //如果存在ok文件就添加到播放列表中
                                            Log.e("FileTool", "getOnlineResourceList: -----333---------->" )
                                            if (isImage(path)) {
                                                Log.e("FileTool", "getOnlineResourceList: -----333-----11----->" )
                                                resouceBean.type = FileType.IMAGE
                                            } else if (isVideo(path)) {
                                                Log.e("FileTool", "getOnlineResourceList: -----333---222------->" )
                                                resouceBean.type = FileType.VIDEO
                                            }
                                            var playTime = 5
                                            try {
                                                playTime = imageDetail.playTime.toInt()
                                            } catch (e: java.lang.Exception) {
                                                e.printStackTrace();
                                            }
                                            resouceBean.playTime = playTime
                                            Log.e("FileTool", "getOnlineResourceList: -----4444---------->" )
                                        }
                                        Log.e("FileTool", "getOnlineResourceList: -----55555---------->" )
                                        resouceList.add(resouceBean)
                                    }
                                }

                            }

                        }
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return resouceList
        }
    }

    object FileType {
        const val TEXT = 0
        const val IMAGE = 1
        const val GIF = 2
        const val VOICE = 3
        const val VIDEO = 4
        const val JS = 5
        const val APP = 10
        const val TEXT_FILE = 11
        const val PDF = 101
    }

//    class ResouceBean(){
//        var path:String=""
//        var type:Int=0
//        constructor(path:String,type:Int):this(){
//            this.path=path
//            this.type=type
//        }
//    }

}